import React from 'react';
import PropTypes from 'prop-types';
import $$ from '../../../utils';

const defaultImages = {
  '1': require('../../../assets/images/yay.jpg'),
  '2': require('../../../assets/images/avatar.jpg'),
};

export default class DefaultImage extends React.Component {

  static propTypes = {
    defaultIndex: PropTypes.string,
    src: PropTypes.string,
  };

  static defaultProps = {
    defaultIndex: '1',
    src: '',
  };

  constructor(props) {
    super(props);
    this.state = {
      src: props.src ? props.src : '',
    }
  }

  componentWillReceiveProps(props){
    this.setState({src: props.src ? props.src : '',});
  }


  handleImageLoaded = () => {
    //加载完毕
  }

  handleImageErrored = () => {
    //加载失败
    this.setState({
      src: defaultImages[this.props.defaultIndex],
    });
  }

  render() {
    let props = this.props;
    let {src} = this.state;
    return (
      <img
        {...props}
        src={src}
        onLoad={this.handleImageLoaded}
        onError={this.handleImageErrored}
      />
    );
  }
}
